
# 地址管理相关视图：包含地址列表、创建、删除
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, get_object_or_404
from LogisticsCard.models import Address


@login_required
def address_list_view(request):
    """
    地址列表视图，展示当前用户的所有地址。
    :param request: HttpRequest对象
    :return: 渲染地址列表页面
    """
    from LogisticsCard.models import Customer
    customer = Customer.objects.filter(user=request.user).first()
    addresses = Address.objects.filter(customer=customer, delete_at__isnull=True).order_by('-created_at') if customer else Address.objects.none()
    return render(request, 'address/index.html', {'addresses': addresses})


@login_required
def address_create_view(request):
    """
    地址创建视图，处理地址表单提交。
    :param request: HttpRequest对象
    :return: 渲染地址创建页面或跳转到列表
    """
    if request.method == 'POST':
        receiver = request.POST.get('receiver')
        phone = request.POST.get('phone')
        address_detail = request.POST.get('address')
        remark = request.POST.get('remark', '')
        Address.objects.create(
            user=request.user,
            receiver=receiver,
            phone=phone,
            address=address_detail,
            remark=remark,
            delete_at=None
        )
        return redirect('address_list')
    return render(request, 'address/create.html')


@login_required
def address_delete_view(request, address_id):
    """
    地址删除视图，删除指定ID的地址。
    :param request: HttpRequest对象
    :param address_id: 地址ID
    :return: 跳转到地址列表页面
    """
    from django.utils import timezone
    address = get_object_or_404(Address, id=address_id, user=request.user, delete_at__isnull=True)
    address.delete_at = timezone.now()
    address.save()
    return redirect('address_list')
